<?php
namespace app\common\logic\cloud;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class BaseCloudLogic{
    
    protected $auth = '';
    
    //服务端域名不能修改哦
    protected $api = 'https://cloud.vipcard.cloud';
    
    protected $client;
    
    protected $params;

    public function __construct() {
        $file = root_path().'auth.txt';
        if(file_exists($file)){ //获取
            $this->auth = trim(file_get_contents($file));
        }
        $this->client = new Client(['base_uri'=> $this->api,'verify' => false,'timeout'  => 30.0]);
        $this->params['auth_token'] = $this->auth;
    }
    
    protected function getParams($params){
        return array_merge($params, $this->params);
    }
    
    protected function error($msg){
        throw new \think\Exception($msg);
    }
    
    protected function download($api,$params = [],$file){
        $response = $this->client->post($api,['save_to'=>$file,'query'=> $this->getParams($params)]);
        if(file_exists($file)){
            return true;
        }
        return false;
    }


    protected function request($api,$params = [],$auth = true){
        $response = $this->client->request('POST',$api,[
           'query'=>$auth == true ?  $this->getParams($params) : $params, 
        ]);
        $data = json_decode($response->getBody(), true);
        if($data['code'] == 200){
            return $data['data'];
        } else {
            $this->error($data['msg']);
        }
    }

    public function register($params = []){
        $params['host'] = $_SERVER['HTTP_HOST'];
        return $this->request('/platform/api/register',$params,false);
    }
    
    public function initData(){
       return $this->request('/platform/api/initData');
    }
    
}